package io.noties.markwon.app.samples;

import com.noties.markwon.wrapper.text.Spanned;

import io.noties.markwon.Markwon;
import io.noties.markwon.app.sample.Tags;
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample;
import io.noties.markwon.image.ImagesPlugin;
import io.noties.markwon.sample.annotations.MarkwonArtifact;
import io.noties.markwon.sample.annotations.MarkwonSampleInfo;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;

/**
 * @author: yangrui
 * @function: ToastDynamicContentSample
 * @date: 2021/3/23
 */
@MarkwonSampleInfo(
  id = "20200627074017",
  title = "Markdown in Toast (with dynamic content)",
  description = "Display markdown in a `android.widget.Toast` with dynamic content (image)",
  artifacts = {MarkwonArtifact.CORE, MarkwonArtifact.IMAGE},
  tags = {Tags.toast, Tags.hack}
)
class ToastDynamicContentSample extends MarkwonTextViewSample {

  @Override
  public void render() {
    final String md = "" +
      " # Head!\n" +
      "![alt](${BuildConfig.GIT_REPOSITORY}/raw/master/art/markwon_logo.png) \n" +
      "Do you see an image? ☝\n";

    final Markwon markwon = Markwon.builder(context)
      .usePlugin(ImagesPlugin.create())
      .build();

    final Markwon markdown = (Markwon) markwon.toMarkdown(md);

    final ToastDialog toast = new ToastDialog(context).setText(markdown.toString());

    // try to obtain textView
    final Text textView = (Text) toast.getComponent();
    CharSequence sequence = markdown.toString() + "";
    if (textView != null) {
      markwon.setParsedMarkdown(textView, (Spanned) sequence);
    }

    // finally show toast (at this point, if we didn't find TextView it will still
    // present markdown, just without dynamic content (image))
    toast.show();
  }

  public Text getTextView(ToastDialog toastDialog) {
    Component component = toastDialog.getComponent();
    if (component instanceof Text) {
      return (Text) component;
    }
    if (component instanceof ComponentContainer) {
      int count = ((ComponentContainer) component).getChildCount();
      for (int i = 0; i < count; i++) {
        Component child = ((ComponentContainer) component).getComponentAt(i);
        if (child instanceof Text) {
          return (Text) child;
        }
      }
    }
    return null;
  }
}